package com.robot.member.controller;

import com.alibaba.fastjson.JSON;
import com.robot.member.client.MerchantClient;
import com.robot.member.pojo.Member;
import com.robot.member.pojo.MerchantApply;
import com.robot.member.pojo.client.Industry;
import com.robot.member.service.MemberService;
import com.robot.member.service.MerchantApplyService;
import entity.PageResult;
import entity.Result;
import entity.Status;
import entity.StatusCode;
import io.jsonwebtoken.Claims;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import util.GeoHashUtil;
import util.String2JsonUtil;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.Map;

/**
 * 商户入驻申请merchant_apply控制器层
 *
 * @author wuyunbin
 */
@RestController
@CrossOrigin
@RequestMapping("/merchant_apply")
public class MerchantApplyController {
    @Autowired
    private MerchantApplyService merchantApplyService;
    @Autowired
    private MemberService memberService;

    @Autowired
    private MerchantClient merchantClient;

    @Autowired
    private HttpServletRequest request;

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    /**
     * 查询全部数据
     *
     * @return
     */
    @RequestMapping(method = RequestMethod.GET)
    public Result findAll() {
        return new Result(StatusCode.SUCCESS_QUERY, merchantApplyService.findAll());
    }

    /**
     * 分页+多条件查询
     *
     * @param searchMap 查询条件封装
     * @param page      页码
     * @param size      页大小
     * @return 分页结果
     */
    @RequestMapping(value = "/search/{page}/{size}", method = RequestMethod.POST)
    public Result findSearch(@RequestBody Map searchMap, @PathVariable int page, @PathVariable int size) {
        Page<MerchantApply> pageList = merchantApplyService.findSearch(searchMap, page, size);
        return new Result(StatusCode.SUCCESS_QUERY, new PageResult<>(pageList.getTotalElements(), pageList.getContent()));
    }

    /**
     * 根据条件查询
     *
     * @param searchMap
     * @return
     */
    @RequestMapping(value = "/search", method = RequestMethod.POST)
    public Result findSearch(@RequestBody Map searchMap) {
        return new Result(StatusCode.SUCCESS_QUERY, merchantApplyService.findSearch(searchMap));
    }

    /**
     * 查看商家入驻申请列表
     *
     * @return
     */
    @GetMapping("application/{page}/{size}")
    public Result application(@PathVariable int page, @PathVariable int size) {
        Claims claims = (Claims) request.getAttribute("robot_member");
        if (claims == null) {
            return new Result(StatusCode.ERROR_TOKEN_EXPIRED);
        }
        logger.info("claims.getId()=" + claims.getId());
        //前端调用findByToken接口检查过了,所以这里不再对会员是否存在和状态进行判断

        Page<MerchantApply> pageData = merchantApplyService.findAllByMemberIdAndDeletedAtIsNullOrderByUpdatedAtDesc(claims.getId(), page, size);
        return new Result(StatusCode.SUCCESS_QUERY, new PageResult<>(pageData.getTotalElements(), pageData.getContent()));
    }

    /**
     * 查看商家入驻申请详情
     */
    @RequestMapping(value = "{id}", method = RequestMethod.GET)
    public Result findMerchantApplyById(@PathVariable String id) {
        Claims claims = (Claims) request.getAttribute("robot_member");
        if (claims == null) {
            return new Result(StatusCode.ERROR_TOKEN_EXPIRED);
        }
        logger.info("claims.getId()=" + claims.getId());
        //前端调用findByToken接口检查过了,所以这里不再对会员是否存在和状态进行判断

        MerchantApply merchantApplyInDb = merchantApplyService.findByIdAndMemberIdAndDeletedAtIsNull(id, claims.getId());
        logger.info("merchantApplyInDb=" + merchantApplyInDb);
        if (merchantApplyInDb == null) {
            return new Result(StatusCode.ERROR_RECORD_DOES_NOTE_EXIST);
        }
        return new Result(StatusCode.SUCCESS_QUERY, merchantApplyInDb);
    }

    /**
     * 初审提交资料
     *
     * @param apply
     */
    @RequestMapping(value = "", method = RequestMethod.PUT)
    public Result add(@RequestBody MerchantApply apply) {
        Claims claims = (Claims) request.getAttribute("robot_member");
        if (claims == null) {
            return new Result(StatusCode.ERROR_TOKEN_EXPIRED);
        }
        logger.info("claims.getId()=" + claims.getId());
        //前端调用findByToken接口检查过了,所以这里不再对会员是否存在和状态进行判断

        Member memberInDb = memberService.findById(claims.getId());
        logger.info("memberInDb=" + memberInDb);

        Status status = merchantApplyService.checkBaseInfo(apply);
        if (status != null) {
            return new Result(status);
        }

        //判断行业是否存在
        Industry industryInDb = JSON.parseObject(merchantClient.thirdFindIndustryById(apply.getIndustryId()), Industry.class);
        logger.info("industryInDb=" + industryInDb);
        if (industryInDb == null || industryInDb.getDeletedAt() != null) {
            return new Result(StatusCode.ERROR_INDUSTRYID_INVALID);
        }
        apply.setIndustryName(industryInDb.getName());
        apply.setMemberId(memberInDb.getId());
        apply.setRecommendId(memberInDb.getRecommendId());

        //对经纬度进行编码
        GeoHashUtil geoHashUtil = new GeoHashUtil();
        String geoHash = geoHashUtil.encode(Double.parseDouble(apply.getLatitude()), Double.parseDouble(apply.getLongitude()));
        apply.setLongitude(apply.getLongitude());
        apply.setLatitude(apply.getLatitude());
        apply.setGeoHash(geoHash);
        apply.setHalfGeoHash(geoHashUtil.halfGeoHash(Double.parseDouble(apply.getLatitude()), Double.parseDouble(apply.getLongitude())));

        merchantApplyService.add(apply);
        return new Result(StatusCode.SUCCESS_APPLY);
    }

    /**
     * 初审失败修改资料
     *
     * @param apply
     */
    @RequestMapping(value = "firstTrial/{id}", method = RequestMethod.PUT)
    @Transactional(rollbackFor = Exception.class)
    public Result firstTrial(@RequestBody MerchantApply apply, @PathVariable String id) {
        Claims claims = (Claims) request.getAttribute("robot_member");
        if (claims == null) {
            return new Result(StatusCode.ERROR_TOKEN_EXPIRED);
        }
        logger.info("claims.getId()=" + claims.getId());
        //前端调用findByToken接口检查过了,所以这里不再对会员是否存在和状态进行判断

        MerchantApply merchantApplyInDb = merchantApplyService.findByIdAndMemberIdAndDeletedAtIsNull(id, claims.getId());
        logger.info("merchantApplyInDb=" + merchantApplyInDb);
        if (merchantApplyInDb == null) {
            return new Result(StatusCode.ERROR_RECORD_DOES_NOTE_EXIST);
        }
        String merchantApplyStatusFirstTrialSuccess = "1";
        if (merchantApplyStatusFirstTrialSuccess.equals(merchantApplyInDb.getStatus())) {
            return new Result(StatusCode.ERROR, "初审已通过,请补全信息");
        }
        //判断手机号
        if (apply.getPhone() != null && !"".equals(apply.getPhone()) && !merchantApplyInDb.getPhone().equals(apply.getPhone())) {
            Status status = merchantApplyService.checkPhoneUsed(apply.getPhone());
            if (status != null) {
                return new Result(status);
            }
        } else {
            apply.setPhone(merchantApplyInDb.getPhone());
        }

        //判断行业是否存在
        if (apply.getIndustryId() != null && !"".equals(apply.getIndustryId())) {
            Industry industryInDb = JSON.parseObject(merchantClient.thirdFindIndustryById(apply.getIndustryId()), Industry.class);
            logger.info("industryInDb=" + industryInDb);
            if (industryInDb == null || industryInDb.getDeletedAt() != null) {
                return new Result(StatusCode.ERROR_INDUSTRYID_INVALID);
            }
            apply.setIndustryName(industryInDb.getName());
        }

        merchantApplyService.update(apply, merchantApplyInDb);

        return new Result(StatusCode.SUCCESS);
    }

    /**
     * 二审失败修改资料
     *
     * @param apply
     * @return
     */
    @RequestMapping(value = "secondTrial/{id}", method = RequestMethod.PUT)
    @Transactional(rollbackFor = Exception.class)
    public Result secondTrial(@RequestBody MerchantApply apply, @PathVariable String id) {
        //检查凭证是否争取
        Claims claims = (Claims) request.getAttribute("robot_member");
        if (claims == null) {
            return new Result(StatusCode.ERROR_TOKEN_EXPIRED);
        }
        logger.info("claims.getId()=" + claims.getId());
        //前端调用findByToken接口检查过了,所以这里不再对会员是否存在和状态进行判断

        logger.info(apply.toString());
        //过滤数据是否合法
        Status status = merchantApplyService.checkApply(apply);
        if (status != null) {
            return new Result(status);
        }

        MerchantApply merchantApplyInDb = merchantApplyService.findSecondTrialApplyByIdAndMemberIdAndStatus(id, claims.getId());
        logger.info("merchantApplyInDb=" + merchantApplyInDb);
        if (merchantApplyInDb == null) {
            logger.info("merchant is not exist");
            return new Result(StatusCode.ERROR_RECORD_DOES_NOTE_EXIST);
        }

        String images = apply.getImages();
        apply.setImages(String2JsonUtil.string2Json(images));
        logger.info(apply.getImages());

        merchantApplyService.update(apply, merchantApplyInDb);

        return new Result(StatusCode.SUCCESS);
    }

    /**
     * 删除
     *
     * @param id
     */
    @RequestMapping(value = "deleteMerchantApply/{id}", method = RequestMethod.PUT)
    public Result delete(@PathVariable String id) {
        Claims claims = (Claims) request.getAttribute("robot_member");
        if (claims == null) {
            return new Result(StatusCode.ERROR_TOKEN_EXPIRED);
        }
        logger.info("claims.getId()=" + claims.getId());
        //前端调用findByToken接口检查过了,所以这里不再对会员是否存在和状态进行判断

        MerchantApply merchantApplyInDb = merchantApplyService.findByIdAndMemberIdAndDeletedAtIsNull(id, claims.getId());
        logger.info("merchantApplyInDb=" + merchantApplyInDb);
        if (merchantApplyInDb == null) {
            return new Result(StatusCode.ERROR_RECORD_DOES_NOTE_EXIST);
        }
        merchantApplyInDb.setDeletedAt(LocalDateTime.now());
        merchantApplyService.update(merchantApplyInDb);
        return new Result(StatusCode.SUCCESS_DELETED);
    }

    /**
     * 检验是否字段补全
     *
     * @param merchantApply
     * @return
     */
    public boolean invalidFieldsNotNull(MerchantApply merchantApply) {
        //商户类型 0-充送 1-折扣
        if (merchantApply.getType() == null || "".equals(merchantApply.getType())) {
            return false;
        }
        //json vip1=会员折扣率 vip2=会长折扣率
        if (merchantApply.getRate() == null || "".equals(merchantApply.getRate())) {
            return false;
        }
        /*//授信额度
        if (merchantApply.getCredit() == null || "".equals(merchantApply.getCredit())) {
            return false;
        }
        //开户行名称
        if (merchantApply.getBankName() == null || "".equals(merchantApply.getBankName())) {
            return false;
        }
        //银行账号
        if (merchantApply.getBankAccount() == null || "".equals(merchantApply.getBankAccount())) {
            return false;
        }
        //户名
        if (merchantApply.getAccountName() == null || "".equals(merchantApply.getAccountName())) {
            return false;
        }
        //账户类型 0-对私 1-对公
        if (merchantApply.getAccountType() == null || "".equals(merchantApply.getAccountType())) {
            return false;
        }*/
        return true;
    }
}
